package com.ruoyi.config;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import java.security.Principal;
import java.util.Map;

/**
 * 将连接请求的用户id作为Principal
 */
public class CustomHandshakeHandler extends DefaultHandshakeHandler {

    @Override
    protected Principal determineUser(
            ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
        // 获取例如 wss://localhost/websocket/1 订阅地址
        // 中的最后一个用户 id 参数作为用户的标识,
        // 为实现发送信息给指定用户做准备
        String uri = request.getURI().toString();
        int startIndex = uri.indexOf("endpointChat/");
        int uid = -1;
        if (startIndex != -1) {
            // 截取 "endpointChat/" 后面的部分
            String subString = uri.substring(startIndex + "endpointChat/".length());

            // 使用正则表达式提取数字部分
            String[] parts = subString.split("/");

            if (parts.length > 0) {
                String numericPart = parts[0];
                // 将提取的字符串转换为整数
                try {
                    uid = Integer.parseInt(numericPart);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    throw e;
                }
            }
        }
        int finalUid = uid;
        return () -> String.valueOf(finalUid);
    }

}
